package com.mvc.interceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Pattern;

/**
 * 用于方法的拦截器,实现拦截器接口
 */
public class MappedHandlerInterceptor implements HandlerInterceptor, Comparable<MappedHandlerInterceptor> {
	/**
	 * order 表示 过滤器的顺序，默认10  越小越优先
	 */
	protected int order = 10;  // 排序用
	
	protected String[] includedUrl;   // 要进行拦截的url
	protected String[] excludedUrl;   // 要排除拦截的url
	
	
	protected HandlerInterceptor interceptor;  // 实际的拦截器，外部传入
	
	
	public MappedHandlerInterceptor() {
	}
	
	// 构造方法，必须传入3个参数
	public MappedHandlerInterceptor(String[] includedUrl, String[] excludedUrl, HandlerInterceptor interceptor) {
		this.includedUrl = includedUrl;
		this.excludedUrl = excludedUrl;
		this.interceptor = interceptor;
		
	}
	
	
	public int getOrder() {
		return order;
	}
	
	public void setOrder(int order) {
		this.order = order;
	}
	
	// 检查查找的url 是否在拦截范围内，优先检查排除url列表  ，然后再检查拦截url列表  , 都没查到也算false 不进行拦截
	public boolean match(String lookupUrl) {
		// 后期改造再实现 * 号这种模糊匹配方案
		if (excludedUrl != null) {
			for (int i = 0; i < excludedUrl.length; i++) {
				if (excludedUrl[i].contains("*")) {
					String pattern = excludedUrl[i].replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*?");
					if (Pattern.matches(pattern, lookupUrl)) {
						return false;
					}
				} else {
					if (excludedUrl[i].equals(lookupUrl)) {
						return false;
					}
				}
			}
		}
		if (includedUrl != null) {
			for (String include : includedUrl) {
				if (include.contains("*")) {
					String pattern = include.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*?");
					if (Pattern.matches(pattern, lookupUrl)) {
						return true;
					}
				} else {
					if (include.equals(lookupUrl)) {
						return true;
					}
				}
			}
		}
		
		
		// 都没查到也算 false
		return false;
	}
	
	
	// 实际的拦截工作 委托给外部传入的真实拦截器
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return this.interceptor.preHandle(request, response);
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object result) throws Exception {
		this.interceptor.postHandle(request, response, result);
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Exception ex) throws Exception {
		this.interceptor.afterCompletion(request, response, ex);
	}
	
	
	/**
	 * 给一个比较接口，用来给拦截器排序
	 */
	
	@Override
	public int compareTo(MappedHandlerInterceptor o) {
		return (this.order - o.getOrder());
	}
}
